package com.lvmama.pangolin.timer.processor;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.lvmama.pangolin.busi.config.ConfigManager;
import com.lvmama.pangolin.busi.timer.TimerManager;
import com.lvmama.pangolin.busi.timer.TimerManagerAssist;
import com.lvmama.pangolin.common.StringTools;
import com.lvmama.pangolin.entity.City_Model;
import com.lvmama.pangolin.entity.JobConfig;
import com.lvmama.pangolin.entity.LogVO;
import com.lvmama.pangolin.entity.TaskSequence;
import com.lvmama.pangolin.entity.Timer;
import com.lvmama.pangolin.service.CityService;
import com.lvmama.pangolin.service.JobConfigService;
import com.lvmama.pangolin.service.OperLogService;
import com.lvmama.pangolin.service.TaskSequenceService;
import com.lvmama.pangolin.service.TimerService;
import com.lvmama.pangolin.timer.CommonJob;
import com.lvmama.pangolin.util.HttpSignUtil;
import com.lvmama.pangolin.util.HttpsUtil;
import com.lvmama.pangolin.util.SpringContextUtil;

public class TimerFission extends CommonJob {

	@Autowired
	private JobConfigService jobConfigService;
	@Autowired
	private TimerService timerService;
	@Autowired
	private TaskSequenceService taskSequenceService;
	@Autowired
	private CityService cityService;
	@Autowired
	private OperLogService operLogService;
	
	
	private Logger logger = Logger.getLogger(TimerFission.class);
	@Override
	public void runJob(JobExecutionContext context, String parameter) 
	{
		logger.info("任务分裂开始...");
		String jobCode  = (String)context.getJobDetail().getJobDataMap()
							.get(TimerManager.JOB_CODE);
		String configParam = (String) context.getJobDetail().getJobDataMap()
				.get(TimerManager.JOB_DATAKEY);
		
		String syscode=System.getProperties().getProperty("SYSCODE");
		syscode = StringTools.isValid(syscode)?syscode:"PUBLIC";
		
		if(timerService == null)
		{
			timerService = (TimerService) SpringContextUtil.getBean(TimerService.class);
		}
		Map<String,Object> timerParam = new HashMap<String,Object>();
		timerParam.put("job_code", jobCode);
		timerParam.put("job_type", "1");
		timerParam.put("timer_valid", "1");
		timerParam.put("syscode", syscode);
		List<String> statusList = new ArrayList<String>();
		statusList.add("0");
		statusList.add("1");
		statusList.add("2");
		statusList.add("3");
		timerParam.put("timer_status", statusList);
		List<Timer> timerL = timerService.queryTimerGroupByTaskId(timerParam);
		boolean lastTaskComplete = true;
		if(timerL != null && !timerL.isEmpty())
		{
			if(timerL.get(0).getGroup_count() > 0)
			{
				lastTaskComplete = false;
			}
			
		}
		if(lastTaskComplete)
		{
			fissionTimer(jobCode,syscode,configParam);
		}
		else
		{
			delayTimer(context);
			fissionTimer(jobCode,syscode,configParam);
		}
		logger.info("任务分裂结束...");

	}
	
	private void delayTimer(JobExecutionContext context)
	{
		
		try
		{
			String timerCode  = (String)context.getJobDetail().getJobDataMap()
					.get(TimerManager.TIMER_CODE);
			String taskId  = (String)context.getJobDetail().getJobDataMap()
					.get(TimerManager.TASK_ID);
			LogVO log = new LogVO();
			log.setBatch_num(taskId);
			log.setTask_id(taskId);
			//任务生成异常
			log.setLog_type("F");
			log.setError_code("0001");
			log.setError_desc("任务分裂生成新任务失败，上次同类型任务未完成，请检查处理！");
			log.setTimer_code(timerCode);
			log.setTask_date(new Date());
			log.setCompany_code("LMM_C_CODE");
			log.setBusi_type("门票");
			if(operLogService == null )
			{
				operLogService = (OperLogService) SpringContextUtil.getBean(OperLogService.class);
			}
			operLogService.insertOperLog(log);
			
			sendLog(log);
			
		}
		catch (Exception e)
		{
			logger.error("插入日志表失败！",e);
		}
		logger.info("上次同类型任务未完成，请检查处理！");
	}
	
	private void sendLog(LogVO log)
	{
		try
		{
			String flag = ConfigManager.getInstance().getParamValue("OPER_LOG", "SENDLOG","0");
			if("0".equals(flag))
			{
				return ;
			}
			String url = ConfigManager.getInstance().getParamValue("OPER_LOG", "URL","http://rhino.lvmama.com/scrapy/?");
			
			if(log != null)
			{
				Map<String,Object> param = new HashMap<String,Object>();
				param.put("type", "LOG");
				param.put("log_type", log.getLog_type());
				param.put("company_code", log.getCompany_code());
				param.put("busi_type", log.getBusi_type());
				param.put("product_id", log.getProduct_id());
				param.put("commodity_id", log.getCommodity_id());
				param.put("url", log.getUrl());
				param.put("ip", log.getIp());
				param.put("batch_num", log.getBatch_num());
				param.put("timer_code", log.getTimer_code());
				param.put("error_code", log.getError_code());
				param.put("error_desc", log.getError_desc());
				param.put("remark", log.getRemark());
				param.put("task_id", log.getTask_id());
				param.put("task_date", log.getTask_date());
				param.put("insert_time", log.getInsert_time());
				
				String paramStr = HttpSignUtil.getSignFromMap(param);
				String requestURL = url + paramStr;
				requestURL = requestURL.replaceAll(" ", "%20");
				HttpsUtil.requestGet(requestURL);
				
			}
			
		}catch (Exception e)
		{
			logger.error("发送数据失败！ "+ log.toString());
		}
		
		
	}
	
	
	private void fissionTimer(String jobCode,String syscode,String configParam)
	{
		Map<String,String> param = new HashMap<String,String>();
		param.put("job_code", jobCode);
		param.put("job_type", "1");
		param.put("job_valid", "1");
		param.put("syscode", syscode);
		
		if(jobConfigService == null)
		{
			jobConfigService = (JobConfigService) SpringContextUtil.getBean(JobConfigService.class);
		}
		if(taskSequenceService == null)
		{
			taskSequenceService = (TaskSequenceService) SpringContextUtil.getBean(TaskSequenceService.class);
		}
		if(cityService == null)
		{
			cityService = (CityService) SpringContextUtil.getBean(CityService.class);
		}
		List<JobConfig> jobconfigs = jobConfigService.queryJobconfig(param);
		List<Timer> timerList = new ArrayList<Timer>();
		if(jobconfigs != null && !jobconfigs.isEmpty())
		{
			//获取抓取范围参数，0表示分裂关心产品所在区域，1表示全站所有区域
			String scope = ConfigManager.getInstance().getParamValue(configParam, "CITY_SCOPE","0");
			String businessCode = ConfigManager.getInstance().getParamValue(configParam, "BUSINESS_CODE","TICKET");
			Timer tv = null;
			int sequenceId = 0;
			try
			{
				TaskSequence taskSequence = new TaskSequence();
				taskSequenceService.insertTaskSeqence(taskSequence);
				sequenceId = taskSequence.getId();
			}
			catch (Exception e)
			{
			}
			String task_id = StringTools.addSingleStr(String.valueOf(sequenceId),"0",8,true);
			for (JobConfig jobConfigVO : jobconfigs)
			{
				//任务细分粒度，1城市级别的粒度，2是省份级别粒度
				if("1".equals(jobConfigVO.getJob_granularity()))
				{
					List<City_Model> cityList = null;
					if("0".equals(scope))
					{
						cityList = cityService.queryCityByCareProductBusiness(businessCode);
					}else
					{
						cityList = cityService.queryCityByCon(null);
					}
					if(cityList != null && !cityList.isEmpty())
					{
						for(City_Model city : cityList)
						{
							tv = createTimer(jobConfigVO,task_id,city,"");
							try
							{
								Thread.sleep(10);
							}
							catch (InterruptedException e)
							{
							}
							timerList.add(tv);
							
						}
						
					}
					
				}
				else if ("2".equals(jobConfigVO.getJob_granularity()))
				{
					
				}
				
				
			}
			
		}
		TimerManagerAssist timerAssist = new TimerManagerAssist();
		if(!timerList.isEmpty())
		{
			Set<Date> sliceSet = timerAssist.spiderTimeSliceSet(null,"spider_time_config");
			Iterator<Date> iterator = sliceSet.iterator();
			int length = timerList.size();
			Date execDate = null;
			String corn = null;
			for (Timer timerVO : timerList)
			{
				timerVO.setTask_timer_count(length);
				if(iterator.hasNext())
				{
					execDate = iterator.next();
				}
				else
				{
					iterator = sliceSet.iterator();
					if(iterator.hasNext())
					{
						execDate = iterator.next();
					}
					
				}
				if(execDate != null)
				{
					corn = StringTools.generateCorn(execDate);
					timerVO.setTimer_cron(corn);
				}
				
				
			}
			
			timerService.insertTimerList(timerList);
			
			for (Timer timerVO : timerList)
			{
				try
				{
					timerAssist.loadValidJob(timerVO);
				}catch(Exception e)
				{
					logger.debug("刷新timer失败！");
				}
				
			}
			
		}
		
	}
	
	private Timer createTimer(JobConfig jobConfigVO,String batch_num,City_Model city,String corn)
	{
		Timer tv = new Timer();
		tv.setSyscode(jobConfigVO.getSyscode());
		tv.setTimer_id(StringTools.getTimerSeq("yyyyMMddHHmmssSSS",true,4));
		tv.setJob_code(jobConfigVO.getJob_code());
		tv.setJob_type(jobConfigVO.getJob_type());
		tv.setTask_id(batch_num);
		tv.setTimer_code(jobConfigVO.getSub_job_code()+"_"+city.getCityId());
		tv.setTimer_seq(jobConfigVO.getJob_seq());
		tv.setTimer_name(jobConfigVO.getJob_name()+"_"+city.getName());
		tv.setExec_mode(jobConfigVO.getExec_mode());
		tv.setTimer_classname(jobConfigVO.getJob_classname());
		tv.setTimer_param(jobConfigVO.getJob_param());
		tv.setTimer_cron(jobConfigVO.getJob_cron());
		tv.setTimer_valid(1);
		tv.setTimer_status("0");
		tv.setRetry_num(jobConfigVO.getRetry_num());
		tv.setRun_num(0);
		tv.setCreate_time(new Date());
		tv.setTimer_granularity(jobConfigVO.getJob_granularity());
		tv.setGranularity_value(city.getCityId());
		tv.setConvert_retry_num(jobConfigVO.getConvert_retry_num());
		tv.setConvert_run_num(0);
		return tv;
		
	}
	

}
